//
//  HTLBView.m
//  轮播_网络版.封装
//
//  Created by dllo on 16/1/25.
//  Copyright © 2016年 HaiTeng. All rights reserved.
//

#import "HTLBView.h"
#import "UIImageView+WebCache.h"

#define KImageViewTAG 300


@interface HTLBView ()<UIScrollViewDelegate>

@property (nonatomic, retain) NSTimer *timer; /**< 定时器 */

@property (nonatomic, retain) UIPageControl *pageControl;

@property (nonatomic, assign) NSInteger currentIndex;

@end



@implementation HTLBView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self drawAllViews];
        //创建timer
        _timer = [[NSTimer alloc]init];
        //        设置默认轮播切换等待时间
        _duration = 3;
        
    }
    return self;
}

/** 绘制全部视图 */
- (void)drawAllViews{
//    self.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.scrollView];
    
}
#pragma mark- 轮播图

#pragma mark 创建滚动视图
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
//        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
        
        //设置滚动视图
        [self setScrollView];
    }
    return _scrollView;
}
#pragma mark 设置滚动视图
- (void)setScrollView{
    _scrollView.pagingEnabled = YES;
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.showsVerticalScrollIndicator = NO;
    _scrollView.bounces = NO;
    _scrollView.delegate = self;
    //Blck 实现 接收传过来的数据数组.
    __weak HTLBView *temp = self;
    self.sendScrollImageDataArray = ^(NSMutableArray *array){
        temp.imagesArray = array;
        temp.scrollView.contentSize = CGSizeMake(temp.frame.size.width * (temp.imagesArray.count + 2), temp.frame.size.height);
        for (int i = 0; i < temp.imagesArray.count + 2; i ++) {
            
            if (i == 0) {
                
                UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, temp.frame.size.width, temp.frame.size.height)];
                imgView.userInteractionEnabled = YES;
                [imgView sd_setImageWithURL:[NSURL URLWithString:temp.imagesArray.lastObject] placeholderImage:[UIImage imageNamed:@"PlaceHolder_Other_Ht"]];
                imgView.tag = KImageViewTAG + i;
                //添加手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:temp action:@selector(tapAction:)];
                [imgView addGestureRecognizer:tap];
                [temp.scrollView addSubview:imgView];
                
                
            }else if (i == temp.imagesArray.count + 1){
                
                
                UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(self.frame.size.width * (temp.imagesArray.count + 1), 0, temp.frame.size.width, temp.frame.size.height)];
                imgView.userInteractionEnabled = YES;
                [imgView sd_setImageWithURL:[NSURL URLWithString:temp.imagesArray.firstObject] placeholderImage:[UIImage imageNamed:@"PlaceHolder_Other_Ht"]];
                imgView.tag = KImageViewTAG + i;
                //添加手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:temp action:@selector(tapAction:)];
                [imgView addGestureRecognizer:tap];
                [temp.scrollView addSubview:imgView];
                
                
                
            }else{
                
                UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(temp.frame.size.width * i, 0, temp.frame.size.width , temp.frame.size.height)];
                imgView.userInteractionEnabled = YES;
                [imgView sd_setImageWithURL:[NSURL URLWithString:temp.imagesArray[i - 1]] placeholderImage:[UIImage imageNamed:@"PlaceHolder_Other_Ht"]];
                imgView.tag = KImageViewTAG + i;
                //添加手势
                UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:temp action:@selector(tapAction:)];
                [imgView addGestureRecognizer:tap];
                [temp.scrollView addSubview:imgView];
            }
            
            
            
        }
        //创建页面控制器
        [temp addSubview:temp.pageControl];
        
        //启动定时器
        temp.timer = [NSTimer scheduledTimerWithTimeInterval:temp.duration target:temp selector:@selector(carouselFromTimer:) userInfo:temp repeats:YES];
    };
  
    
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    //开始拖动，timer暂停
    [self.timer invalidate];
}


- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    self.timer = nil;
    
    
    if (_scrollView.contentOffset.x == self.frame.size.width * (self.imagesArray.count + 1)) {
        _scrollView.contentOffset = CGPointMake(self.frame.size.width, 0);
    }else if (_scrollView.contentOffset.x == 0){
        _scrollView.contentOffset = CGPointMake(self.frame.size.width * self.imagesArray.count, 0);
    }
    
    
    if (_scrollView.contentOffset.x == self.frame.size.width * 1) {
        _pageControl.currentPage = 0;
        self.currentIndex = self.pageControl.currentPage;
        
    }else if (_scrollView.contentOffset.x == self.frame.size.width * (self.imagesArray.count - 2)){
        _pageControl.currentPage = self.imagesArray.count - 3;
        self.currentIndex = self.pageControl.currentPage;
    }else{
        _pageControl.currentPage = _scrollView.contentOffset.x / self.frame.size.width - 1;
        self.currentIndex = self.pageControl.currentPage;
    }
    
    
    //   启动timer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.duration target:self selector:@selector(carouselFromTimer:) userInfo:self repeats:YES];
}
#pragma mark Timer驱动轮播方法
- (void)carouselFromTimer:(id)sender{
    self.currentIndex ++;
    if (self.currentIndex == self.imagesArray.count) {
        self.currentIndex = 0;
    }
    self.pageControl.currentPage = self.currentIndex;
    NSInteger page = self.pageControl.currentPage + 1;
 
    //首尾动画过度效果
    [UIView beginAnimations:@"MainScrollViewAnimation_ht" context:nil];
    [UIView setAnimationDuration:1]; //设置动画持续时间
    [self.scrollView setContentOffset:CGPointMake(self.frame.size.width * page, 0)];
    [UIView commitAnimations];
    
    
}

- (void)setDuration:(NSTimeInterval)duration{
    [self.timer invalidate];
    self.timer = nil;
    _duration = duration;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:_duration target:self selector:@selector(carouselFromTimer:) userInfo:self repeats:YES];
}
#pragma mark tap手势触发方法
- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    NSUInteger index = tap.view.tag - KImageViewTAG;
    //将当前的轮播图和当前轮播图下标传递给外界
    if (_htLBdelegate != nil && [_htLBdelegate respondsToSelector:@selector(LBView:DidTapTishImageAtIndex:)]) {
        [_htLBdelegate LBView:self DidTapTishImageAtIndex:index];
    }
    
}
#pragma mark 页面控制器
- (UIPageControl *)pageControl{
    if (_pageControl == nil) {
        self.pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(self.scrollView.center.x,CGRectGetMaxY(self.scrollView.frame) - 20, 0, 20)];
        
        _pageControl.numberOfPages = self.imagesArray.count;
        _pageControl.pageIndicatorTintColor = [UIColor darkGrayColor];
        _pageControl.currentPageIndicatorTintColor = [UIColor redColor];
        
        
    }
    return _pageControl;
}


@end
